package www.lagou.app;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.junit.Test;
import www.lagou.entity.Account;
import www.lagou.utils.DateUtils;
import www.lagou.utils.DruidUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class TransactionTest {

    /**
     * 通过卡号获取账户余额
     */
    @Test
    public void test1() {

        Connection con = null;
        //执行查询
        try {
            //获取QueryRunner对象
            QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
            //编写SQL语句
            String sql = "select * from account where card = ?";
            Account ac1 = qr.query(sql, new BeanHandler<Account>(Account.class), "1122334455");
            Account ac2 = qr.query(sql, new BeanHandler<Account>(Account.class), "55443332211");
            double balance1 = ac1.getBalance();
            System.out.println("未转账前两方的余额为：");
            System.out.println("转出方：" + balance1 + "\t转入方：" + ac2.getBalance());
            if (balance1 < 5000) {
                System.out.println("余额不足！");
            } else {
                //获取连接
                con = DruidUtils.getConnection();
                //开启事务
                con.setAutoCommit(false);
                String sql1 = "update account set balance = balance - ? where card = ?";
                //设置占位符
                Object[] param1 = {5000, "1122334455"};
                //执行update
                qr.update(sql1, param1);

                String sql2 = "update account set balance = balance + ? where card = ?";
                Object[] param2 = {5000, "55443332211"};
                qr.update(sql2, param2);
                System.out.println("转账成功！");
                //提交事务
                con.commit();
                //把转出方插入transaction表中
                String insert = "insert into transaction values(?,?,?,?,?)";
                Object[] o1 = {null, "1122334455", "转出", 5000, DateUtils.getDateFormart()};
                qr.update(insert, o1);
                //把转入方插入transaction表中
                Object[] o2 = {null, "55443332211", "转入", 5000, DateUtils.getDateFormart()};
                qr.update(insert, o2);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //出现异常就回滚
            try {
                assert con != null;
                con.rollback();
                System.out.println("转账失败！");
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        } finally {
            DruidUtils.close(con);
        }
    }
}
